<?php
/**
 * @author Matteo Vigoni <mattevigo@gmail.com>
 * @package PHPorcupine
 * @version 2.0
 *
 * The class Blogpost implements the simple post on the blog as a generic post
 * that consist in title, subtitle and body.
 * This class manage meta information too like tags, categories, user auth, modified times...
 *
 * Extend this class and override the doPost() function to provide custom blogpost to your blog.
 */
require_once($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."config_dbentity.php");
require_once(DBENTITY);

// Social Interfaces //////////////////////////////////////////////////////////////////////////
//require_once CORE_PATH.DS.'social'.DS.'FacebookInterface.php';
//require_once CORE_PATH.DS.'social'.DS.'TwitterInterface.php';
require_once CORE_PATH.DS.'Plugin.php';
require_once CORE_PATH.DS.'Seed.php';							       
																	   #old school importing...
// Class Definition ///////////////////////////////////////////////////////////////////////////
class Blogpost extends DBEntity implements Plugin /*, FacebookInterface, TwitterInterface */
{
	// tabella
	const TABLE = 'blogposts';
	const PRIMARY_KEY = 'blogpost_id';

	var $table = 'blogposts';
	var $primary_key = 'blogpost_id';

	const AUTH_GROUP = "blog";

	public $type = NULL;	// Blogpost type

	public $usr = NULL;		// User object
	
	public $seed = NULL;	// Seed object

	/**
	 * Costruttore
	 *
	 * @param $db
	 * @param $id
	 * @return unknown_type
	 */
	public function __construct( DB $db, $table=NULL, $primary_key=NULL, Seed $seed=NULL, $id=NULL, User $usr=NULL )
	{
		if( $table == NULL ) $table = $db->prefix().$this->table;
		else $table = $db->prefix().$table;
		
		if( $primary_key == NULL ) $primary_key = $this->primary_key;
		
		// Get the Seed
		if( $seed != NULL )
		{
			$this->setSeed( &$seed );
			
			// Constructor for DBEntity
			parent::__construct( $db, $table, $primary_key, $seed->getObjectId( "Blogpost" ) );
		}
		else
		{
			// Constructor for DBEntity
			parent::__construct( $db, $table, $primary_key, $id );
		}
			
		$this->usr = $usr;
	}

	public function setType( $type )
	{
		$this->type = new $type( $this->getDB() );
	}

	public function getType()
	{
		return $this->type;
	}

	public function setUser( User $usr )
	{
		$this->usr = $usr;
	}

	public function getUser()
	{
		return $this->usr;
	}

	public function doGet( User $user=NULL, Session $session=NULL )
	{
		global $_GET;

		return "{\"status\":\"Not Implemented\"}";
	}

	/**
	 *
	 * @param User $user
	 * @param Session $session
	 * @return string a JSON rappresentation of the performed action
	 *
	 * @throws DBEntityException if user don't the rights or not a user specified
	 */
	public function doPost( User $user=NULL, Session $session=NULL )
	{
		global $_POST;

		$json = "";

		// User ////////////////////////////////////////////////////////////////////////
		$usr = NULL;
		if( $user == NULL )
		{
			if( $this->getUser() != NULL )
			{
				$usr = $this->getUser();

				if( !$usr->isInGroup( self::AUTH_GROUP ))
				{
					throw new DBEntityException("You don't have the rights");
				}
			}
			else
			{
				throw new DBEntityException("No User specified");
			}
		}
		else
		{
			$usr = $user;
		}

		$this->set('user_id', $usr->getId());	# set user_id in the object
		$this->set('blogpost_class', $_POST['classpath']);

		// Blogpost ///////////////////////////////////////////////////////////////////
		$this->set('blogpost_title', $_POST['blogpost_title']);
		$this->set('blogpost_subtitle', $_POST['blogpost_subtitle']);
		$this->set('blogpost_body', $_POST['blogpost_body']);

		$this->set('blogpost_modified', time());

		if( $this->is_new )
		{
			$this->set('blogpost_date', time());
			$json = "{\"status\":\"New Blogpost added\"}";
		}
		else
		{
			$json = "{\"status\":\"Blogpost modified\"}";
		}

		return $json;
	}

	public function store($id=NULL)
	{
		parent::store($id);
	}

	// STATIC FUNCTIONS /////////////////////////////////////////////////////////////////////////

	/**
	 *
	 * @param DB $db
	 * @param unknown_type $orderby
	 * @param unknown_type $filter
	 * @param unknown_type $limit
	 * @param unknown_type $from
	 */
	public static function getArray( DB $db, $orderby=NULL, $filter=1, $limit=NULL, $from=0 )
	{
		$array = array();
		

		$seed_table = $db->prefix()."seeds";
		$table = $db->prefix().self::TABLE;
		$sql = "SELECT s.seed_id , b.blogpost_id, s.seed_classpath " .
				"FROM $table b, $seed_table s WHERE s.seed_id=b.seed_id AND $filter ";
		
		if( $orderby != NULL ) $sql .= "ORDER BY $orderby ";
		
		if( $limit != NULL) $sql .= "LIMIT $from, $limit ";

		$result = $db->query( $sql );
		while( $assoc = mysql_fetch_assoc( $result ) )
		{
			try
			{
				// class of the item
				import( $assoc['seed_classpath'] );
				$class = Seed::getClassname( $assoc['seed_classpath'] );
					
				$seed = new Seed( &$db, NULL, NULL, $assoc['seed_id'] );
				$item = new $class( &$db, NULL, NULL, $seed );
				$item->setSeed( &$seed );
					
				$array[ $assoc['seed_id'] ] = $item;
			}
			catch(Exception $e)
			{
				echo "Error: {$e->getMessage()} at line {$e->getLine()} in {$e->getFile()}<br />";
				echo "Trace:<br />".nl2br($e->getTraceAsString())."<br />";
			}
		}

		return $array;
	}
	
	// 
	
	public function getTitle()
	{
		return $this->get('blogpost_title');
	}
	
	public function getSubTitle()
	{
		return $this->get('blogpost_subtitle');
	}
	
	public function getBody()
	{
		return $this->get('blogpost_body');
	}

	// SEEDED ///////////////////////////////////////////////////////////////////////////////////

	/**
	 * 
	 */
	public function getSeedId()
	{
		return $this->get('seed_id');
	}

	/**
	 * 
	 */
	public function getSeed()
	{
		if( $this->seed != NULL )
		{
			return $this->seed;	
		}
		else
		{
			return new Seed( $this->getDB(), NULL, NULL, $this->getSeedId() );
		}
	}

	/**
	 * 
	 * @param Seed $s
	 */
	public function setSeed( Seed $s )
	{
		$this->set('seed_id', $s->getId() );
		$this->seed = $s;
	}

	// SOCIAL ///////////////////////////////////////////////////////////////////////////////////

	///////// Facebook Functions ///////////

	public function setFacebook( Facebook $f )
	{
		$this->set('facebook', $f);
	}

	public function updateStatus( User $usr )
	{
		//throw new NotImplementedException("function updateStatus() not implemented");
		$this->get('facebook');
	}

	////////// Twitter Functions ///////////

	public function getTwitterEmail()
	{
		throw new NotImplementedException("function getTwitterEmail() not implemented");
	}

	public function getTwitterUsername()
	{
		throw new NotImplementedException("function getTwitterUsername() not implemented");
	}

	public function getTwitterPassword()
	{
		throw new NotImplementedException("function getTwitterPassword() not implemented");
	}

	public function tweet( User $usr )
	{
		throw new NotImplementedException("function tweet() not implemented");
	}
}
